<?php
declare (strict_types = 1);

namespace app\common\libs;


/**
 * CURL请求
 *
 * @Author tanruizheng
 * @DateTime 2021-07-19
 */
class CurlService
{

    /**
     * CURL请求
     *
     * @Author tanruizheng
     * @DateTime 2021-07-28
     * @param [type] $url
     * @param string $method
     * @param array $data
     * @param boolean $header
     * @param integer $timeout
     * @return void
     */
    public static function request($url, $method = 'get', $data = [], $header = false, $timeout = 15){
        $ch = curl_init();
        //请求路径
        curl_setopt($ch, CURLOPT_URL, $url);
        //请求时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //设置header头部
        if($header){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        //https请求
        if(strpos($url, 'https') === false){
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        }
        //请求方式
        $method = strtolower($method);
        if($method == 'post'){
            if(is_array($data)){
                $data = http_build_query($data);
            }
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        list($content, $status) = [curl_exec($ch), curl_getinfo($ch)];
        curl_close($ch);
        if(intval($status['http_code'] === 200)){
            return $content;
        }else{
            return false;
        }
    }

    /**
     * get请求
     *
     * @Author tanruizheng
     * @DateTime 2021-07-28
     * @param [type] $url
     * @param array $data
     * @param boolean $header
     * @param integer $timeout
     * @return void
     */
    public static function getRequest($url, $data = [], $header = false, $timeout = 15){
        if(!empty($data)){
            $url .= strpos($url, '?') === false ? '?' : '&';
            $url .= is_array($data) ? http_build_query($data) : $data;
        }
        return self::request($url, 'get', [], $header, $timeout);
    }

    /**
     * post请求
     *
     * @Author tanruizheng
     * @DateTime 2021-07-28
     * @param [type] $url
     * @param array $data
     * @param boolean $header
     * @param integer $timeout
     * @return void
     */
    public static function postRequest($url, $data = [], $header = false, $timeout = 15){
        return self::request($url, 'post', $data, $header, $timeout);
    }
}
